namespace PHSRAG.Insight21.Humans
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
	using System.Collections;

	/// <summary>
	///		Summary description for ConsentFormPublisher.
	/// </summary>
	public partial class ConsentFormPublisher : System.Web.UI.UserControl
	{
		#region Constants
		private const string ProcessIdsKey = "processIds_020C8F00-2A70-4ab8-9118-BBA438E0E0E0";
		#endregion

		#region Instance variables
		private Policy.ICachePolicy	pageCachePolicy;
		private Policy.ICachePolicy cachePolicy;
		private int protocolId;
		private Protocol protocol;
		private ArrayList protocolConsentForms;
		#endregion

		#region Protected instance variables
		/// <summary>button to save the changes made to the grid</summary>
		
		/// <summary>grid that displays the consent forms tied to the protocol</summary>
		#endregion

		#region Properties
		/// <summary>
		/// Sets the id of the protocol for which details will be displayed
		/// </summary>
		public int ProtocolID
		{
			set
			{
				protocolId = value;
			}
		}

		/// <summary>
		/// Gets the protocol .If it's not already in the cache, it loads it up based on the protocolId passed to the page, and caches the object
		/// </summary>
		private Protocol Protocol
		{
			get
			{
				string cacheKey = Protocol.ProtocolKey;
				protocol = cachePolicy.GetCachedObject(cacheKey) as Protocol;

				if ((protocol == null) || (protocolId != protocol.Id))
				{
					protocol = new Protocol(cachePolicy);
					protocol.Load(Utility.DataAccess.GetConnectionString(), protocolId);
					cachePolicy.Cache(cacheKey, protocol);
				}
				return protocol;
			}
		}

		/// <summary>
		/// DataSource for process names displayed in the grid. 
		/// </summary>
		public DataTable ProcessIds
		{
			get
			{
				DataTable processIds = (DataTable)pageCachePolicy.GetCachedObject(ProcessIdsKey);
				if (processIds == null)
				{
					processIds = Protocol.GetProcessIds(protocolId, pageCachePolicy);
					DataRow dr = processIds.NewRow();
					processIds.Rows.InsertAt(dr, 0); //blank row
					pageCachePolicy.Cache(ProcessIdsKey, processIds);
				}
				return processIds;
			}
		}
		#endregion

		#region Page Events
		/// <summary>
		/// Retrieve the consent forms associated with the protocol and bind them to the grid.
		/// </summary>
		/// <param name="sender">Object that raised the event</param>
		/// <param name="e">Arguments associated with the event.</param>
		protected void OnPageLoad(object sender, System.EventArgs e)
		{
			protocolConsentForms = Humans.Protocol.GetElectronicOnlyProtocolDocuments(protocolId, FormsManagement.Constants.AttachmentType.ConsentForm, pageCachePolicy);
			controlsPanel.Enabled = true;
			
			if (!IsPostBack)
			{
				pageCachePolicy.UnCache(ProcessIdsKey);
				BindGrid();
			}
		}
		#endregion

		#region Web Form Designer generated code
		/// <summary>
		/// Initialization
		/// </summary>
		/// <param name="e">Arguments associated with the event</param>
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			pageCachePolicy = (Policy.ICachePolicy)Session[Policy.Names.PageCachePolicyKey];
			cachePolicy = (Policy.ICachePolicy)Session[Policy.Names.CachePolicyKey];
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.consentForms.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.OnConsentFormsItemCommand);
			this.consentForms.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnConsentFormsItemDataBound);
			this.save.Click += new System.Web.UI.ImageClickEventHandler(OnSaveClick);
			this.Load += new System.EventHandler(this.OnPageLoad);

		}
		#endregion

		#region Private methods
		/// <summary>
		/// Binds all the consent forms tied to the protocol to the grid
		/// </summary>
		private void BindGrid()
		{
			consentForms.DataSource = protocolConsentForms;
			consentForms.DataBind();

		}
		#endregion

		#region Control Events
		/// <summary>
		/// Update the consent forms with the amendment name and published flag as specified in the grid
		/// </summary>
		/// <param name="sender">Object that raised the event</param>
		/// <param name="e">Arguments associated with the event</param>
		private void OnSaveClick(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			for(int i=0; i< consentForms.Items.Count; ++i)
			{
				ProtocolDocument protocolConsentForm = (ProtocolDocument)protocolConsentForms[i];
				DropDownList processName = (DropDownList)consentForms.Items[i].FindControl("processName");
				if (processName.SelectedIndex != -1)
					protocolConsentForm.FormsId = processName.SelectedValue;
				CheckBox published = (CheckBox)consentForms.Items[i].FindControl("published");
				protocolConsentForm.Published = published.Checked;

				protocolConsentForm.Save(Utility.DataAccess.ConnectionString);
			}

			BindGrid();
		}

		
		/// <summary>
		/// Displays the consent form pdf along with the footer
		/// </summary>
		/// <param name="source">Object that raised the event</param>
		/// <param name="e">Arguments associated with the event.</param>
		private void OnConsentFormsItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			if (e.CommandName == "OpenConsentForm")
			{
				Hashtable outgoingData = new Hashtable();
				//outgoingData[Keys.DocumentKey] = Protocol.GetConsentFormWithFooter((ProtocolDocument)protocolConsentForms[e.Item.ItemIndex]);
				outgoingData[Keys.DocumentKey] = UIUtility.GetConsentFormWithFooter(cachePolicy, (ProtocolDocument)protocolConsentForms[e.Item.ItemIndex]);
				cachePolicy.Cache(Keys.IncomingDataKey, outgoingData);

				string script = "\n<script language=JavaScript id='Display'>\n" +
					"var confirmWin = window.open('../Research/DownloadForm.aspx', 'ViewFile', 'resizable=yes, status=yes, toolbar=no, scrollbars=yes'); \n" +
					"</script>";

				if(!Page.ClientScript.IsClientScriptBlockRegistered("Display"))
				{
					//Register the script
					Page.ClientScript.RegisterClientScriptBlock(GetType( ), "Display", script);
				}
			}
		}

		/// <summary>
		/// Show the amendment number, if any, associated with the consent form
		/// </summary>
		/// <param name="source">Object that raised the event</param>
		/// <param name="e">Arguments associated with the event.</param>
		private void OnConsentFormsItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{
				DropDownList processName = (DropDownList)e.Item.FindControl("processName");
				ListItem li = processName.Items.FindByText(((ProtocolDocument)protocolConsentForms[e.Item.ItemIndex]).FormsId);
				if (li != null)
					processName.SelectedIndex = processName.Items.IndexOf(li);
			}
		}

		#endregion
		
	}
}
